package com.frame.geteway.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.frame.common.tools.result.ResultCode;
import com.frame.common.tools.result.ServiceResult;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.util.annotation.NonNull;

/**
 * 网关全局异常处理
 *
 * @auther zhangwj
 * @date 2021/3/30 下午7:50
 */
@Order(-1)
@Configuration
public class GlobalErrorWebExceptionHandler implements ErrorWebExceptionHandler {


    private final ObjectMapper objectMapper;

    public GlobalErrorWebExceptionHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @NonNull
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, @NonNull Throwable e) {
        ServerHttpResponse response = exchange.getResponse();
        if (response.isCommitted()) {
            return Mono.error(e);
        }
        // 设置返回JSON
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        if (e instanceof ResponseStatusException) {
            response.setStatusCode(((ResponseStatusException) e).getStatus());
        }

        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            try {
                return bufferFactory.wrap(objectMapper.writeValueAsBytes(ServiceResult.getFailureResult(ResultCode.RESPONSE_STATUS_ERROR.getCode(), e.getMessage())));
            } catch (JsonProcessingException ex) {
                return bufferFactory.wrap(new byte[0]);
            }
        }));
    }
}
